/*
 * This file is part of Catfish.
 * Copyright (C) 2010 Namazu Studios LLC
 * 
 * Catfish is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as 
 * published by the Free Software Foundation, either version 3 of 
 * the License, or (at your option) any later version.
 * 
 * Catfish is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with Catfish.  If not, please visit:
 *  
 * http://www.gnu.org/licenses/
 *  
 */
package com.namazustudios.catfish.converter;

import java.lang.reflect.Type;

import com.google.appengine.api.datastore.Key;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.namazustudios.catfish.CatfishException;
import com.namazustudios.catfish.reference.WeakReference;

public class WeakReferenceConverter implements Converter<Key, WeakReference<?>> {

    @Inject
    private Injector injector;

    @Override
    public WeakReference<?> load(Type type, WeakReference<?> existing, Key obj) {

        if (existing == null) {
            throw new CatfishException("WeakReferences must not be null prior to unmarshalling.");
        }

        injector.injectMembers(existing);
        existing.setKey(obj);

        return existing;
    }

    @Override
    public Key store(WeakReference<?> obj) {

        if (obj == null) {
            throw new CatfishException("Weakreferences must not be null prior to marshalling.");
        }

        injector.injectMembers(obj);
        return obj.getKey();
    }

}
